import store from '@/store'
import $CONFIG from '@/config'

import {
  visiblePcMusic,
  visibleMobileMusic,
  musicOnce,
  musicMeanwhile
} from '@/utils/krpano'

import { getThemeName, isXiaoMiPhone } from '@/utils'

let bgMusicObj
let bgMusicBtn = false

let sceneAudioObj
let sceneAudioBtn = false

let menuOrPointAudioObj
let menuOrPointAudioBtn = false

// 过滤音乐数据
export const formatUrl = (data) => {
  if(!data) return false

  if (data.indexOf('http') === 0) {
    return data
  }

  if(~data.indexOf('|')) {
    data = data.split('|')[1]
  }
  if(!~data.indexOf('http')) {
    data = $globalconfig.URLS.API + data
  }
  return data
}

const getBgMusic = () => {
  return store.getters.bgMusic || ''
}

const hasBgMusicPlay = () => {
  if( ( getThemeName() == 'app' && visibleMobileMusic() ) || ( getThemeName() == 'pc' && visiblePcMusic() ) ) {
    return true
  }
  return false
}

const changeBgMusicIconStatus = (val) => {
  $CONFIG.toolsBarMenuE.map(item => {
    if(item.type_id == 'bgmusic') {
      item.isActive = val
    }
  })

  $CONFIG.defMenu.map(item => {
    if(item.type_id == 'bgmusic') {
      item.isActive = val
    }
  })

  $CONFIG.pcDefMenu.map(item => {
    if(item.type_id == 'bgmusic') {
      item.isActive = val
    }
  })
}

// 创建背景音乐
const createBgMusicObj = (data) => {
  if(!data) return
  data = formatUrl(data)

  bgMusicObj = new Audio()
  // 是否循环播放
  if (musicOnce()) {
    bgMusicObj.loop = true
  } else {
    bgMusicObj.loop = false
  }
  bgMusicObj.src = data
  bgMusicObj.volume = Number(store.getters.volume.toFixed(1))
  bgMusicObj.id = 'panoBgAudio'
}

// 播放背景音乐
const playBgMusic = () => {
  // if (isXiaoMiPhone()) {
  //   $VM.$vgo.emit('music:audoplay')
  // } else {
  if(bgMusicObj) {
    setTimeout(() => {
      bgMusicObj.play()
      bgMusicBtn = true
      bgMusicObj.status = 'open'
      // $VM.$vgo.emit('bgmusic-icon:toggle', true)
    }, 10)
  }
  // 触发状态修改
  changeBgMusicIconStatus(true)
  // }
}

// 暂停背景音乐
const pauseBgMusic = () => {
  if(bgMusicObj) {
    bgMusicObj.pause()
    bgMusicBtn = false
    bgMusicObj.status = 'close'
    // $VM.$vgo.emit('bgmusic-icon:toggle', false)
  }
  changeBgMusicIconStatus(false)
}

// 初始化播放背景音乐
export const initBgMusic = () => {
  // hasBgMusicPlay()默认开启播放背景音乐
  // musicMeanwhile()=true同时播放
  const curSceneAudio = store.getters.curSceneMusic
  if (curSceneAudio) {
    const data = formatUrl(curSceneAudio)
    if (!sceneAudioObj) {
      createSceneAudio(data)
    }
    playSceneAudio()
    if (hasBgMusicPlay() && musicMeanwhile()) {
      // 背景音乐
      if (!bgMusicObj) {
        createBgMusicObj(getBgMusic())
      }
      playBgMusic()
    }
  } else {
    if (hasBgMusicPlay()) {
      // 背景音乐
      if (!bgMusicObj) {
        createBgMusicObj(getBgMusic())
      }
      playBgMusic()
    }
  }
}

export const toggleBgMusic = () => {
  $VM.$krp.controlsAllVideoin()
  // pauseAllAudio()
  if(!bgMusicObj) {
    createBgMusicObj(getBgMusic())
    playBgMusic()
    // $VM.$vgo.tip('播放背景音乐', 'success')
  }
  console.log(bgMusicBtn)

  let msg = bgMusicBtn ? '暂停背景音乐' : '播放背景音乐'
  // 背景音乐状态
  bgMusicObj.status = bgMusicBtn ? 'close' : 'open'
  $VM.$vgo.tip(msg, 'success')
  bgMusicBtn ? pauseBgMusic() : playBgMusic()

  // bgMusicBtn = !bgMusicBtn
}

// 创建场景音乐
const createSceneAudio = (data) => {
  if(data) {
    sceneAudioObj = new Audio()
    sceneAudioObj.src = data
    sceneAudioObj.loop = true
  }
}

// 播放音频
export const playSceneAudio = () => {
  if(sceneAudioObj) {
    setTimeout(() => {
      sceneAudioObj.play()
      sceneAudioBtn = true

      setTimeout(() => {
        $VM.$vgo.emit('audioicon', true)
        // $VM.$vgo.emit('toggle:musicicon', true)
      }, 1000)
    }, 10)
  }
}

// 暂停音频
export const pauseSceneAudio = () => {
  if(sceneAudioObj) {
    sceneAudioObj.pause()
    sceneAudioBtn = false
    $VM.$vgo.emit('audioicon', false)
    // $VM.$vgo.emit('toggle:musicicon', false)
  }
}

// 初始化场景音乐
export const initSceneAudio = () => {
  let data = store.getters.curSceneMusic
  data = formatUrl(data)
  if(data && !sceneAudioObj) {
    createSceneAudio(data)
  }
  playSceneAudio()
}

// 切换场景解说音频
export const toggleSceneAudio = () => {
  $VM.$krp.controlsAllVideoin()

  let msg = sceneAudioBtn ? '暂停解说' : '播放解说'
  sceneAudioBtn ? pauseSceneAudio() : playSceneAudio()

  $VM.$vgo.tip(msg, 'success')
}

// 创建热点或菜单音乐
const createMenuOrPointAudio = (data) => {
  if(data) {
    menuOrPointAudioObj = new Audio()
    menuOrPointAudioObj.src = data
    menuOrPointAudioObj.loop = false
  }
}

// 播放菜单或热点音频
export const playMenuOrPointAudio = () => {
  // 暂停其他音频
  pauseAllAudio()

  if(menuOrPointAudioObj) {
    setTimeout(() => {
      menuOrPointAudioObj.play()
      menuOrPointAudioBtn = true
    }, 10)
  }
}

// 暂停菜单或热点音频
export const pauseMenuOrPointAudio = () => {
  if(menuOrPointAudioObj) {
    menuOrPointAudioObj.pause()
    menuOrPointAudioBtn = false
  }
}

// 切换菜单或热点音频
export const toggleMenuOrPointAudio = (data) => {
  data = formatUrl(data)

  pauseAllAudio()

  if(!menuOrPointAudioObj) {
    createMenuOrPointAudio(data)
    playMenuOrPointAudio()
  } else {
    menuOrPointAudioObj.src = data
    menuOrPointAudioBtn ? pauseMenuOrPointAudio() : playMenuOrPointAudio()
    if(menuOrPointAudioBtn) {
      replaySceneOrBgMusic()
    }
  }
  // menuOrPointAudioBtn = !menuOrPointAudioBtn
}

// 关闭菜单或热点音频后，播放场景音乐还是背景音乐
export const replaySceneOrBgMusic = () => {
  let curSceneAudio = ''
  if (store.getters && store.getters.curSceneMusic) {
    curSceneAudio = store.getters.curSceneMusic
  }
  playSceneOrBgMusic(curSceneAudio || '')
}

// 暂停所有音频
export const pauseAllAudio = () => {
  pauseSceneAudio()
  pauseBgMusic()
  pauseMenuOrPointAudio()
}

// 场景切换触发音乐播放
export const playSceneOrBgMusic = (data) => {
  if (store.getters.themeId == 11 || store.getters.themeId == 12) return

  pauseMenuOrPointAudio()
  pauseSceneAudio()
  data = formatUrl(data)
  // 背景音乐
  if(!data) {
    if (!bgMusicObj) {
      createBgMusicObj(getBgMusic())
    }
    console.log('没有场景音乐')
    // 处理切换场景时，背景音乐如果被手动关了，不再开启
    if (window.sessionStorage.getItem('ISUSER') !== '1') {
      playBgMusic()
    }
  } else {
    // scene music
    // 如果有背景音乐，musicMeanwhile()为true同时播放
    console.log('4-----------------')
    if (!musicMeanwhile()) {
      pauseBgMusic()
    } else {
      if (!bgMusicObj) {
        createBgMusicObj(getBgMusic())
      }
      // 处理切换场景时，背景音乐如果被手动关了，不再开启
      if (window.sessionStorage.getItem('ISUSER') !== '1') {
        playBgMusic()
      }
    }

    if(!sceneAudioObj) {
      createSceneAudio(data)
      playSceneAudio()
    } else {
      sceneAudioObj.src = data
      playSceneAudio()
    }
  }
}

// 监听用户点击，触发音乐播放
let isPlay = false
const touchFunc = () => {
  isPlay = true
  console.log('用户点击，只触发一次')
  replaySceneOrBgMusic()
  window.removeEventListener('touchstart', touchFunc, false)
}
if (!isPlay) {
  window.addEventListener('touchstart', touchFunc, false)
}

// 修改背景音乐的状态
export const updateBgMusicStatus = () => {
  if(!bgMusicObj) {
    createBgMusicObj(getBgMusic())
  }
  setTimeout(() => {
    pauseBgMusic()
  }, 10)
}

// 销毁音乐
export const destroyAllAudio = () => {
  pauseAllAudio()
  if(bgMusicObj) {
    bgMusicObj.load()
  }
}

export const audioManage = new class {
  constructor() {
    this.state = {curPlay: []}
  }
  pauseAll() {
    this.state.audioObj = {bgMusicObj, sceneAudioObj, menuOrPointAudioObj}
    for (const key in this.state.audioObj) {
      const item = this.state.audioObj[key]
      if (item && !item.paused) {
        this.state.curPlay.push(item)
        item.muted = true
      }
    }
  }
  continueAll() {
    this.state.curPlay.map(i => i && (i.muted = false))
    this.state.curPlay = []
  }
}

// (手绘图，VR旅游，总览图)背景音乐---start
let handdrawBgmusicObj = null
// 创建手绘图背景音乐
const createHanddrawBgmusicObj = data => {
  if (!data) {
    return false
  }
  handdrawBgmusicObj = new Audio()
  handdrawBgmusicObj.loop = true
  handdrawBgmusicObj.volume = 1.0
  handdrawBgmusicObj.src = data
}

// 播放手绘图背景音乐
export const playHanddrawBgmusic = () => {
  if(handdrawBgmusicObj) {
    handdrawBgmusicObj.play()
  }
}

// 暂停手绘图背景音乐
export const pauseHanddrawBgmusic = () => {
  if (handdrawBgmusicObj) {
    handdrawBgmusicObj.pause()
  }
}

// 初始化手绘图背景音乐
export const initHanddrawBgmusic = data => {
  if (!data) {
    return false
  }
  if (!handdrawBgmusicObj) {
    createHanddrawBgmusicObj(data)
  }
  playHanddrawBgmusic()
}
// (手绘图，VR旅游，总览图)背景音乐---end
